<?php

namespace App\Console\Commands\Rabbit;

use Illuminate\Console\Command;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

class Publisher extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'rabbitmq:publisher:weixin';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
      $connection = new AMQPStreamConnection('rabbitmq', '5672',
        'guest', 'guest', '/');

      $channel = $connection->channel();

      $channel->set_ack_handler(function (AMQPMessage $message) {
        echo 'Message acked with content ' . $message->body . PHP_EOL;
      });

      $channel->set_nack_handler(function (AMQPMessage $message) {
        echo 'Message nacked with content ' . $message->body . PHP_EOL;
      });

      $channel->set_return_listener(function() {
        echo 'Message return.......' . PHP_EOL;
      });

      $channel->confirm_select();

      foreach (range(1, 10) as $index) {
        $message = new AMQPMessage('i am weixin message: ' . $index);
        $channel->basic_publish($message, 'exchange.direct',
          '', true);
      }

      $channel->wait_for_pending_acks_returns();

    }
}
